package com.glq1218.rental.service.impl;

import com.glq1218.article.entity.Article;
import com.glq1218.article.mapper.ArticleMapper;
import com.glq1218.domain.RentalResult;
import com.glq1218.rental.service.RentalService;
import com.glq1218.user.entity.User;
import com.glq1218.user.mapper.UserMapper;
import com.glq1218.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author glq1218
 * @description TODO
 * @since 2023/5/4 10:14
 */
@Service("rentalService")
@RequiredArgsConstructor
public class RentalServiceImpl implements RentalService {
    private final ArticleMapper articleMapper;
    private final UserMapper userMapper;

    /**
     * @param articleId 物品id
     * @return 租赁结果
     */
    @Override
    public RentalResult rental(Long articleId) {
        Article article = articleMapper.selectById(articleId);
        User user = userMapper.selectById(article.getUserId());
        Long userId = SecurityUtils.getUserId();
        if (user.getId().equals(userId)) {
            throw new RuntimeException("不可以租赁自己发布的物品");
        }
        if (article.getStatus() == 2) {
            throw new RuntimeException("物品已经租出");
        }
        article.setStatus(Byte.decode("2"));
        boolean update = articleMapper.updateById(article) > 0;
        boolean insert = articleMapper.rental(article.getId(), userId) > 0;
        if (!update && !insert) {
            throw new RuntimeException("租赁失败");
        }
        return RentalResult.builder()
                .username(user.getUsername())
                .nickname(user.getNickname())
                .phone(user.getPhone())
                .email(user.getEmail())
                .articleName(article.getName())
                .build();
    }
}
